/**
 * 线
 * */

export default {
    data() {
        return {
        }
    },
    created() {
        this.handlersMA = null
    },
    methods: {
        getCenterByCar3(positions) {
            var x = 0
            var y = 0
            var z = 0
            var len = positions.length - 1

            for (var i = 0; i < len; i++) {
                x += positions[i].x
                y += positions[i].y
                z += positions[i].z
            }

            return new Cesium.Cartesian3(x / len, y / len, z / len)
        },
        Bearing: function(from, to) {
            var angle = -Math.atan2(Math.sin(from.lng - to.lng) * Math.cos(to.lat),
                Math.cos(from.lat) * Math.sin(to.lat) - Math.sin(from.lat) * Math.cos(to.lat) * Math.cos(from.lng - to.lng))
            if (angle < 0) {
                angle += Math.PI * 2.0
            }
            return angle
        },
        getAngle: function(p1, p2, p3) {
            // var cartographic1 = Cesium.Cartographic.fromCartesian(p1)
            // var cartographic2 = Cesium.Cartographic.fromCartesian(p2)
            // var cartographic3 = Cesium.Cartographic.fromCartesian(p3)

            // var bearing21 = this.Bearing(cartographic2, cartographic1)
            // var bearing23 = this.Bearing(cartographic2, cartographic3)
            var bearing21 = this.Bearing(p2, p1)
            var bearing23 = this.Bearing(p2, p3)
            var angle = bearing21 - bearing23
            if (angle < 0) {
                angle += Math.PI * 2.0
            }
            return angle
        },
        getDistance: function(point1, point2) {
            var startcartographic = this.transformWGS84ToCartographic(point1)
            var endcartographic = this.transformWGS84ToCartographic(point2)
            /** 根据经纬度计算出距离**/
            var geodesic = new Cesium.EllipsoidGeodesic()
            geodesic.setEndPoints(startcartographic, endcartographic)
            var s = geodesic.surfaceDistance
            s = Math.sqrt(
                Math.pow(s, 2) +
                // Math.pow(endcartographic.height - startcartographic.height, 2)
                0
            )
            return s
        },
        getPositionsArea: function(positions) {
            var area = 0
            var length = positions.length
            for (var i = 0; i < length - 2; i++) {
                var nextOne = (i + 1) % length
                var nextTwo = (i + 2) % length

                var totalAngle = this.getAngle(positions[0], positions[nextOne], positions[nextTwo])

                var dis_temp1 = this.getDistance(positions[0], positions[nextOne])
                var dis_temp2 = this.getDistance(positions[nextOne], positions[nextTwo])

                area += dis_temp1 * dis_temp2 * Math.sin(totalAngle) / 2.0
            }
            return Math.abs(area)
        },
        onToolMA() {
            var isNew = true
            var positions = []
            var hierarchy
            var entityLine, drawLayer, dataSourceName
            var addInfoPoint = cartesian => {
                const _labelEntity = {
                    position: cartesian,
                    eventName: 'DrawTool',
                    dataSourceName: dataSourceName
                }

                _labelEntity.point = {
                    pixelSize: 2,
                    outlineColor: Cesium.Color.BLUE,
                    outlineWidth: 2,
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
                }
                drawLayer.entities.add(_labelEntity)
            }
            var addRes = () => {
                const _labelEntity = {
                    position: this.getCenterByCar3(positions),
                    eventName: 'DrawTool',
                    dataSourceName: dataSourceName
                }

                _labelEntity.point = {
                    pixelSize: 2,
                    outlineColor: Cesium.Color.BLUE,
                    outlineWidth: 2,
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
                }
                var pointDegs = this.transformCartesianArrayToWGS84Array(positions)
                var area = this.getPositionsArea(pointDegs)
                var txt = ''
                if (area < 10000) {
                    txt = (area / 1).toFixed(1) + 'm²'
                } else {
                    txt = (area / 1000000).toFixed(3) + 'km²'
                }
                _labelEntity.label = {
                    text: txt,
                    show: true,
                    showBackground: true,
                    font: '14px monospace',
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                    verticalOrigin: Cesium.VerticalOrigin.CENTER
                    // pixelOffset: new Cesium.Cartesian2(-40, -10) // left top
                }
                drawLayer.entities.add(_labelEntity)
            }
            this.handlersMA = new Cesium.ScreenSpaceEventHandler(this.$viewer.scene.canvas)
            // left
            this.handlersMA.setInputAction(movement => {
                var cartesian = this.getCatesian3FromPX(movement.position)
                if (cartesian && cartesian.x) {
                    if (isNew) {
                        isNew = false
                        positions = []
                        hierarchy = new Cesium.PolygonHierarchy()
                        dataSourceName = 'DrawToolMA' + new Date().getTime()
                        drawLayer = new Cesium.CustomDataSource(dataSourceName)
                        entityLine = drawLayer.entities.add({
                            eventName: 'DrawTool',
                            dataSourceName: dataSourceName,
                            polyline: {
                                positions: new Cesium.CallbackProperty((time, result) => {
                                    return positions
                                }, false),
                                width: 2,
                                material: Cesium.Color.WHITE.withAlpha(0.8),
                                clampToGround: true
                            },
                            polygon: {
                                hierarchy: new Cesium.CallbackProperty((time, result) => {
                                    return hierarchy
                                }, false),

                                material: Cesium.Color.WHITE.withAlpha(0.2),
                                classificationType: Cesium.ClassificationType.BOTH
                            }
                        })
                        this.$viewer.dataSources.add(drawLayer)
                        positions.push(cartesian.clone())
                        hierarchy.positions.push(cartesian.clone())
                    }
                    addInfoPoint(cartesian, dataSourceName)
                    positions.push(cartesian.clone())
                    hierarchy.positions.push(cartesian.clone())
                }
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

            this.handlersMA.setInputAction(movement => {
                var cartesian = this.getCatesian3FromPX(movement.endPosition)
                if (positions.length >= 2) {
                    if (cartesian && cartesian.x) {
                        positions.pop()
                        positions.push(cartesian)
                        hierarchy.positions.pop()
                        hierarchy.positions.push(cartesian)
                    }
                }
            }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
            // right
            this.handlersMA.setInputAction(movement => {
                if (positions.length === 0) return
                if (positions.length < 3) {
                    this.$viewer.dataSources.remove(drawLayer, true)
                } else {
                    positions.pop()
                    positions.push(positions[0])
                    hierarchy.positions.pop()
                    entityLine.polyline.positions = positions // 解决不能删除单根线的问题
                    entityLine.polygon.hierarchy = hierarchy
                    addRes()
                }
                this.offToolMA()
                this.onToolMA()
            }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
        },
        offToolMA() {
            if (this.handlersMA) {
                this.handlersMA.destroy()
                this.handlersMA = null
            }
        }
    }
}
